#!/usr/local/bin/python
# -*- coding: utf-8 -*-

'''
    用户对象定义
'''
import logging, traceback
from tornado.escape import json_encode,json_decode

import util, log, code_define
import const
import mysqlHelper
import time
#import datetime
from props_manager import *

logger = logging.getLogger(__name__)

class User:
    ''''''
    
    def __init__(self, socket_id, userinfo, request, bLogin=False):
      
        self.m_socket_id = socket_id
        self.m_request = request
        
        self.m_userinfo = userinfo
        
        self.m_userinfo["age"] = UserManager.countAge(userinfo.get('birthday'))     #计算年龄
        self.m_userinfo["magic"] = None #道具魔法卡信息
        self.m_day_first_login = False  #是否当日首次登陆
        
        self.m_props_privilege_list = [] #正在使用的特权道具列表(如T台胸花名字) ["brooch"]
        
        #self.m_map_my_goods = {}		#我的商品列表    	    Map<商品ID, 信息>        
        #self.m_map_my_goods_type = {}	#我的商品列表-按类型分  Map<商品类型, 信息>		
        
        #self.m_map_my_props = {}		#我的道具列表	        Map<道具类型, 道具对象列表>
        self.m_map_my_using_props = {}	#正在使用中的道具列表            Map<type3, 道具对象>
        
        #self.m_map_my_use_cloth = {}	#身上穿戴的衣物列表 	Map<商品ID, 信息>
        
        self.m_list_bar_see_me = []		#酒吧-看见我的人列表	List<用户ID> (我状态变化,需通知这个队列)     
        self.m_list_bar_i_see = []		#酒吧-我看见的人列表	List<用户ID>          		
        
        self.m_list_bar_ask_i_send = []	#我发出过搭讪请求的列表	List<用户ID>        
        self.m_list_bar_ask_i_recv = []	#向我请求搭讪的用户列表	List<用户ID>        
        self.m_list_bar_user_i_chat = []#我约会过的列表	List<用户ID> (只存在内存,再次约会得到的数值会减少, 暂时没使用)        		
        
        self.m_list_my_attt_uid = []		#我的关注列表	List<用户ID> 
        self.m_map_my_attt = {}				#我的关注列表	map { 123:{"uid":123, "nickname":"xxx", "level":1, "yellow_level": 1}, uid2:{}} 
        self.m_list_attt_me_uid = []        #关注我的列表    List<用户ID>   
        self.m_map_attt_me = {}             #关注关注列表      map { 123:{"uid":123, "nickname":"xxx", "level":1, "yellow_level": 1}, uid2:{}} 
  	
        self.m_list_my_hidden_love_uid = []     #我的暗恋列表    List<用户ID> 
        self.m_map_my_hidden_love = {}          #我的暗恋列表    map { 123:{"uid":123, "nickname":"xxx", "level":1, "yellow_level": 1}, uid2:{}} 
        self.m_list_hidden_love_me_uid = []		#暗恋我的列表    List<用户ID>   
        self.m_map_hidden_love_me = {}		    #暗恋我的列表     map { 123:{"uid":123, "nickname":"xxx", "level":1, "yellow_level": 1}, uid2:{}} 
        
        self.m_list_my_friend_uid = []		#我的好友列表	List<用户ID>      
        self.m_map_my_friend = {}			#我的好友列表   map { 123:{"uid":123, "nickname":"xxx", "level":1, "yellow_level": 1}, uid2:{}}     
        #self.m_list_my_black = []		#黑名单列表		List<用户ID>        		
        
        #self.m_map_house_visit_me = {}	#访问过我的访客历史记录	map<用户ID, 记录>        
        #self.m_map_house_i_visit = {}	#我访问过的房间历史记录	map<用户ID, 记录>        		
        
        #self.m_map_house_steal_me = {}	#偷过我金币的访客记录表	Map<user_id, info*>        
        #self.m_map_house_i_steal = {}	#我偷过金币的房间记录表	Map<user_id, info*>        		
        
        #self.m_map_house_clean_me = {}	#打扫我房间的访客记录表        
        #self.m_map_home_i_clean = {}	#我帮人打扫房间的记录表        		
        
        #self.m_map_leaveword_to_me = {}	#给我的留言列表        
        #self.m_map_i_leaveword = {}		#我给别人的留言列表
        
        self.m_logintime = time.strftime('%Y-%m-%d %H:%M:%S')
        
        self.m_loginTimeHeartBeatMod = int(time.time()) % 60      #登陆时间取模
        if bLogin:
            UserManager.insertMapHearBeat(self.m_loginTimeHeartBeatMod, self.m_userinfo.get("uid"))
      	
        #访客我房间的所有访客记录 (访客来访\留言\打扫\偷钱等记录) #只保留50条记录, 回写DB #查询时候, 返回此给客户端
        #self.m_map_house_log = {}

        
        #----------other---------- 
        self.m_current_place = "default"    #当前所在模块
        
        self.m_bar_state = -1               #酒吧状态 0:单身, 1:约会中, 2:PK中  (-1:退出酒吧/名人堂)
        self.m_bar_room_id = 0              #约会房间ID 
        self.m_task=[]                      #我的任务列表   
        self.m_last_talk = int(time.time())
       
    #------正在使用中的道具列表-----------------
    def getMyUsingProps(self):
        self.m_map_my_using_props = self.getUserInfoToDict("my_props_using")
        return self.m_map_my_using_props
    
    def isMyPropsUsing(self, type3):
        '''是否正在使用一个type3类型的道具(未过期), 0表示无, 1表示有'''
        tmpMyUsingObj = self.m_map_my_using_props.get(type3)
        if tmpMyUsingObj:
            tmpProps = tmpMyUsingObj.get("props")
            if tmpProps:
                if time.time() <= tmpProps.get("limit_time"): #未过期
                     return 1
        return 0
    
    def delMyUsingProps(self, type3):
        '''删除正在使用的某道具'''
        if self.m_map_my_using_props.has_key(type3):
            self.m_map_my_using_props.pop(type3)
            return 1
        return 0
      
    def delAndInsertMyUsingProps(self, type3, tmpMyUsingGoodsObj):
        '''删除， 并插入正在使用的道具'''
        self.delMyUsingProps(type3)
        self.m_map_my_using_props[type3] = tmpMyUsingGoodsObj
        
    def setUserInfoPropMagic(self):
        '''设置道具魔法卡信息'''
        self.m_userinfo['magic'] = self.m_map_my_using_props.get('magic', {}) 

    #------我正在使用的的特权道具列表-----------------
    def addUserInfoPropPrivilege(self, tmpName):
        '''设置道具 正在使用的特权信息(如胸花)'''
        util.inserList(self.m_props_privilege_list, tmpName)
    
    def delUserInfoPropPrivilege(self, tmpName):
        '''设置道具 正在使用的特权信息(如胸花)'''
        util.deleteFromList(self.m_props_privilege_list, tmpName)

    def addUserInfoPropPrivilegeBrooch(self):
        '''胸花'''
        self.addUserInfoPropPrivilege("brooch")
        
    def delUserInfoPropPrivilegeBrooch(self):
        '''胸花'''
        self.delUserInfoPropPrivilege("brooch")
            
    def getUserInfoPropPrivilege(self):
        '''获取道具 正在使用的特权信息(如胸花)'''
        return self.m_props_privilege_list

          
       
    #------我已购买的道具列表-----------------
    def getMyProps(self):
        tmpVal = self.m_userinfo.get("my_props")
        if tmpVal is None:
            tmpVal = {}
        return tmpVal
    
       
    #---名人堂排名数据-----------------------------------------
    def getOrderValue(self):
        '''计算排名的数值--魅力＞好友数＞资产值＞亲友团'''
        tmpTotal = 100000000L * self.getCharm()
        tmpTotal += 10000L * self.getMyFriendListSize()
        tmpTotal += 100L * self.getAssets()
        tmpTotal += self.getCountInvite()
        return tmpTotal
    
       
    #---用户当前模块-----------------------------------------
    def setCurrentPlace(self, place="default"):
        self.m_current_place = code_define.get_place(place)
    
    def getCurrentPlace(self):
        return self.m_current_place
       
    #---用户酒吧状态-----------------------------
    def setUserBarStateSingle(self):
        self.m_bar_state = 0
         
    def setUserBarStateDouble(self):
        self.m_bar_state = 1
        
    def setUserBarStatePK(self):
        self.m_bar_state = 2
        
    def setUserBarStateExit(self):
        self.m_bar_state = -1
        
    def isUserBarStateSingle(self):
        return self.m_bar_state == 0
        
    def isUserBarStateExit(self):
        return self.m_bar_state == -1
        
    def getUserBarState(self):
        return self.m_bar_state

    def isUserNotInBarRoom(self):  #酒吧状态 0:单身, 1:约会中, 2:PK中  (-1:退出酒吧/名人堂)
        '''用户是否在房间中聊天'''
        return self.m_bar_state in [0, -1]
    
    #---用户酒吧约会房间ID----------------------
    def setRoomID(self, room_id):
        self.m_bar_room_id = room_id
    
    def getRoomID(self):
        return self.m_bar_room_id
    
  
    #---用户基本信息--------------------------
    def getUserInfoObj(self):
        return self.m_userinfo
    
    def getUserInfo(self, info):
        return self.m_userinfo.get(info)

    def getUserInfoToInt(self, info):
        '''获取用户基本信息成  整数'''
        tmpVal = self.m_userinfo.get(info, 0)
        return int(tmpVal)
    
    def getUserInfoToStr(self, info):
        '''获取用户基本信息成 字符串对象'''
        tmpVal = self.m_userinfo.get(info, "")
        if isinstance(tmpVal, unicode):
            tmpVal = tmpVal.encode('utf-8')
        return str(tmpVal)
    
    def getUserInfoToDict(self, info):
        '''获取用户基本信息成 字典对象'''
        tmpVal = self.m_userinfo.get(info, {})
        if not isinstance(tmpVal, dict):
            tmpVal = util.jsonDecodeToDict(tmpVal)
        return tmpVal
    
    def getUserInfoToList(self, info):
        '''获取用户基本信息成  数组对象'''
        tmpVal = self.m_userinfo.get(info, [])
        if not isinstance(tmpVal, list):
            tmpVal = util.jsonDecodeToList(tmpVal)
        return tmpVal
        
    #---获取注册来源--(weibo, renren 等)', #新浪weibo:0;腾讯朋友pengyou:1; 人人renren:2; kc:3; 腾讯空间qzone:4
    def getRegfrom(self):    
        tmpVal = self.getUserInfoToStr("regfrom")
        tmpDict = {"weibo":0, "pengyou":1, "renren":2, "kc":3, "qzone":4}
        return tmpDict.get(tmpVal, 0)
        
    #---设置用户属性-  
    def setUserInfo(self, info, val):
        self.m_userinfo[info] = val
    
    #---获取用户穿戴-
    def getMyBodyInfo(self):
        return self.getUserInfoToDict("my_bodyinfo")
    
    #---获取用户备注信息  保存些备注信息, 比如是否得到等级礼包-
    def getRemarkInfo(self):
        return self.getUserInfoToDict("remark_info")
    
    def isGetGiftGoods(self, tmpGoodsLevel):
        '''是否已经获得某等级的等级礼包'''
        tmpRemarkInfoDict = self.getRemarkInfo()    # { "gift_goods":{"10": [1234], "20":[1222]}} 
        tmpGiftGoodsDict = tmpRemarkInfoDict.get("gift_goods")  
        if tmpGiftGoodsDict and isinstance(tmpGiftGoodsDict, dict):
            if tmpGiftGoodsDict.get(str(tmpGoodsLevel)):
                return True
        return False
    
    def addGetGiftGoods(self, tmpGoodsLevel, tmpGoodsIDList):
        '''保存已获得某等级的等级礼包到缓存'''
        if isinstance(tmpGoodsIDList, int):
            tmpList = [tmpGoodsIDList]
        else:
            tmpList = tmpGoodsIDList
                
        tmpUserInfo = self.getUserInfoObj()
        tmpRemarkInfoDict = tmpUserInfo.get("remark_info")
        if tmpRemarkInfoDict is None:
            tmpRemarkInfoDict = {}
            tmpUserInfo["remark_info"] = tmpRemarkInfoDict
         
        tmpGiftGoodsDict = tmpRemarkInfoDict.get("gift_goods")  
        if tmpGiftGoodsDict is None:
            tmpGiftGoodsDict = {}
            tmpRemarkInfoDict["gift_goods"] = tmpGiftGoodsDict
        tmpGiftGoodsDict[str(tmpGoodsLevel)] = tmpList
                
    
    #----获取用户当前勇气值
    def getCurrentCourage(self):
        return util.CountUserUtil.getCurrentCourage(self)     #计算当前勇气值

    #----获取用户当前体力值
    def getCurrentPower(self):
        return util.CountUserUtil.getCurrentPower(self)     #计算当前勇气值    

    #----获取用户当前人品值
    def getCurrentQuality(self):
        return util.CountUserUtil.getCurrentQuality(self)     #计算当前人品值
    
    #----获取用户人缘值
    def getEnergy(self):
        '''DB剩余可增加的关注人数'''
        return self.getUserInfoToInt("energy") 
    
    #20120229新增
    def getEloquence(self):
        '''口才值'''
        return self.getUserInfoToInt("eloquence")
    def getKnowledge(self):
        '''知识值'''
        return self.getUserInfoToInt("knowledge")
    def getConstitution(self):
        '''体质值'''
        return self.getUserInfoToInt("constitution")
    def getMood(self):
        '''情绪值'''
        return self.getUserInfoToInt("mood")
    def getAppearance(self):
        '''外貌值'''
        return self.getUserInfoToInt("appearance")
    
    
    
    
    def getCurrentMaxEnergy(self):
        '''当前的最大'精力(人缘)',，(DB保存的值+我的关注人数), 客户端显示使用'''
        tmpV = self.getEnergy()
        tmpV += self.getMyAtttListSize()
        return tmpV

    #---获取用户等级-
    def getLevel(self):
        return self.getUserInfoToInt("level")  
    
    #---获取用户昵称-
    def getNickname(self):
        return self.getUserInfoToStr("nickname")
    
    #---获取用户经验值-
    def getExp(self):
        return self.getUserInfoToInt("exp")
    
    #---获取用户魅力值-
    def getCharm(self):
        return self.getUserInfoToInt("charm")

    #---获取用户资产值-
    def getAssets(self):
        return self.getUserInfoToInt("assets")

    #---获取用户uid-
    def getUID(self):
        return self.getUserInfoToInt("uid")
    
    #---获取用户socket_id-
    def getSocketID(self):
        return self.m_socket_id    
    
    #---获取用户request-
    def getRequest(self):
        return self.m_request

    #---获取用户相反的性别-
    def getDiffentSex(self):
        if self.getSex() == 1:
            return 0
        else:
            return 1
    
    #---获取用户性别-
    def getSex(self):
        return self.getUserInfoToInt("sex")

    #---获取用户生日-
    def getBirthday(self):
        tmpVal = self.getUserInfoToStr('birthday')
        if not tmpVal:
            tmpVal = "1970-01-01"
        return tmpVal[0:10]
    
    def getAge(self):
        '''获取年龄'''
        return self.getUserInfoToInt("age")
    
    def getCountInvite(self):
        '''获取亲友团数量'''
        return self.getUserInfoToInt("count_invite")
        
    def getCountAtted(self):
        '''获取关注我的人数'''
        return self.getUserInfoToInt("count_atted")
    
    def getProvince(self):
        '''获取地址-省'''
        return self.getUserInfoToStr("province")
    
    def getCity(self):
        '''获取地址-市'''
        return self.getUserInfoToStr("city")
    
    def getAutoInfo(self):
        '''获取当前用户个人特征，用于撮合'''
        myAutoinfo = self.getUserInfoToDict("autoinfo")
        myAutoinfo['province'] = self.getProvince()
        myAutoinfo['city'] = self.getCity()
        myAutoinfo['age'] = self.getAge()
        return myAutoinfo
        
    #---获取用户黄钻信息
    def getYellowLevel(self):
        return self.getUserInfoToInt("yellow_level")
    
    #---用户是否黄钻用户(0不是， 1-7等级)
    def isYellow(self):
        return (self.getUserInfoToInt('yellow_level') > 0)

    #---用户是否年费黄钻  (0不是, 1是)
    def isYellowVip(self):
        return (self.getUserInfoToInt('yellow_vip') == 1)
        
    #---用户是否当日首次登录
    def isDayFirstLogin(self):
        tmpStrDay = self.m_userinfo.get('last_login_time')
        if not tmpStrDay:
            return True 
        return tmpStrDay[0:10] != time.strftime('%Y-%m-%d')
    
    def isRegFinish(self):
        '''是否走完注册流程'''
        tmpRegStepList = self.getUserInfoToList("reg_step")
        tmpLen = len(tmpRegStepList)
        if tmpLen == 0:  #为0 表示已走完注册流程
            return True
        elif tmpLen > 0:
            tmpStepListMust = const.Config_Reg_Step_List_must[0:]               #配置文件获取注册步骤[必须走的步骤]
            if not util.ifListValInOtherList(tmpStepListMust, tmpRegStepList):  #非必走步骤不存在用户的注册步骤，表示已经走完
                return True
        return False  
    

    #---#酒吧-看见我的人列表-(我状态变化,需通知这个队列)---------------------
    def insertBarSeeMeList(self, uid):
        util.inserList(self.m_list_bar_see_me, uid)
        log.print_debug(logger, "User insertBarSeeMeList exec, socket_id:[%s], myuid:[%s], uid:[%s], \nlist:%s" 
                        % (self.getSocketID(), self.getUID(), uid, self.m_list_bar_see_me))
        
    def delBarSeeMeList(self, uid):
        util.deleteFromList(self.m_list_bar_see_me, uid)
        log.print_debug(logger, "User delBarSeeMeList exec, socket_id:[%s], myuid:[%s], uid:[%s], \nlist:%s" 
                        % (self.getSocketID(), self.getUID(), uid, self.m_list_bar_see_me))
  
    def getBarSeeMeList(self):
        return self.m_list_bar_see_me
        
    def clearBarSeeMeList(self):
        del self.m_list_bar_see_me[0:]
    
    #---#酒吧-我看见的人列表-------------------------------------------    
    def getBarISeeList(self):
        return self.m_list_bar_i_see
        
    def insertBarISeeList(self, uid):
        util.inserList(self.m_list_bar_i_see, uid) 
        log.print_debug(logger, "User insertBarISeeList exec, socket_id:[%s], myuid:[%s], uid:[%s], \nlist:%s" 
                        % (self.getSocketID(), self.getUID(), uid, self.m_list_bar_i_see))
      
    
    def delBarISeeList(self, uid):
        util.deleteFromList(self.m_list_bar_i_see, uid)
        log.print_debug(logger, "User delBarISeeList exec, socket_id:[%s], myuid:[%s], uid:[%s], \nlist:%s" 
                        % (self.getSocketID(), self.getUID(), uid, self.m_list_bar_i_see))

    def clearBarISeeList(self):
        del self.m_list_bar_i_see[0:]
        log.print_debug(logger, "User clearBarISeeList exec, socket_id:[%s], myuid:[%s], \nlist:%s" 
                        % (self.getSocketID(), self.getUID(), self.m_list_bar_i_see))
	
    #---#我发出过搭讪请求的列表-------------------------------------------
    def insertBarAskISendList(self, uid):
        util.inserList(self.m_list_bar_ask_i_send, uid)
        log.print_debug(logger, "User insertBarAskISendList exec, socket_id:[%s], myuid:[%s], uid:[%s], \nlist:%s" 
                        % (self.getSocketID(), self.getUID(), uid, self.m_list_bar_ask_i_send))
    
    def delBarAskISendList(self, uid):
        util.deleteFromList(self.m_list_bar_ask_i_send, uid)
        log.print_debug(logger, "User delBarAskISendList exec, socket_id:[%s], myuid:[%s], uid:[%s], \nlist:%s" 
                        % (self.getSocketID(), self.getUID(), uid, self.m_list_bar_ask_i_send))
        
        
    #---#向我请求搭讪的用户列表-------------------------------------------
    def insertBarAskIRecvList(self, uid):
        util.inserList(self.m_list_bar_ask_i_recv, uid)
        log.print_debug(logger, "User insertBarAskIRecvList exec, socket_id:[%s], myuid:[%s], uid:[%s], \nlist:%s" 
                        % (self.getSocketID(), self.getUID(), uid, self.m_list_bar_ask_i_recv))
    
    def delBarAskIRecvList(self, uid):
        util.deleteFromList(self.m_list_bar_ask_i_recv, uid)
        log.print_debug(logger, "User delBarAskIRecvList exec, socket_id:[%s], myuid:[%s], uid:[%s], \nlist:%s" 
                        % (self.getSocketID(), self.getUID(), uid, self.m_list_bar_ask_i_recv))
                
    def isInBarAskIRecvList(self, uid): #判断是否在"向我搭讪队列            
        return uid in self.m_list_bar_ask_i_recv

        
    #---#我约会过的列表	List<用户ID> (只存在内存,再次约会得到的数值会减少)----------------------
    def insertUserIChatList(self, uid):
        util.inserList(self.m_list_bar_user_i_chat, uid)
        log.print_debug(logger, "User insertUserIChatList exec, socket_id:[%s], myuid:[%s], uid:[%s], \nlist:%s" 
                        % (self.getSocketID(), self.getUID(), uid, self.m_list_bar_user_i_chat))
  
	
    #---#我的关注列表-------------------------------------------
    def getMyAtttListUID(self):
		return self.m_list_my_attt_uid[0:]
		
    def setMyAtttMap(self, tmpMap):
        self.m_map_my_attt = tmpMap
        del self.m_list_my_attt_uid[0:]
        for tmpUID in self.m_map_my_attt.keys():
            util.inserList(self.m_list_my_attt_uid, int(tmpUID))
			
    def getMyAtttMap(self):
    	return self.m_map_my_attt

    def insertMyAtttMap(self, tmpUser):
    	'''加入我关注的列表, 如果对方同时在 关注我的列表, 则进入我的好友列表'''
    	if not tmpUser:
    		return 0
    	tmpUID = tmpUser.getUID()
    	if util.inserList(self.m_list_my_attt_uid, tmpUID):
    		tmpInfo = UserManager.createDBFriendItem(tmpUser, "my_attt")  #构建格式{uid:{"uid":1, "nickname":"xxx", "level":2, "yellow_level":2, "col":""}}
    		self.m_map_my_attt[str(tmpUID)] = tmpInfo.get(tmpUID)
    		
    		if self.isInAtttMeListUID(tmpUID):  #对方同时在 关注我的列表, 则进入我的好友列表
    			self.insertMyFriendMap(tmpUser)
    			return 1
    	return 0   #0: 单方关注, 1: 双方关注
    
    def delMyAttt(self, uid):
        util.deleteFromList(self.m_list_my_attt_uid, uid)
        util.deleteFromDict(self.m_map_my_attt, str(uid))
    
    def isInMyAtttListUID(self, uid):
    	'''uid是否在我的关注队列'''
    	return uid in self.m_list_my_attt_uid
		
    def getMyAtttListSize(self):
        return len(self.m_list_my_attt_uid)
            
    #---#关注我的列表-------------------------------------------
    def getAtttMeListUID(self):
		return self.m_list_attt_me_uid[0:]

    def getAtttMeMap(self):
        return self.m_map_attt_me
						
    def setAtttMeMap(self, tmpMap):
        self.m_map_attt_me = tmpMap
        del self.m_list_attt_me_uid[0:]
        for tmpUID in self.m_map_attt_me.keys():
        	util.inserList(self.m_list_attt_me_uid, int(tmpUID))

    def insertAtttMeMap(self, tmpUser):
        '''加入关注我的列表, 如果对方同时在 我关注的列表, 则进入我的好友列表'''
        if not tmpUser:
        	return
        tmpUID = tmpUser.getUID()
        if util.inserList(self.m_list_attt_me_uid, tmpUID):
        	tmpInfo = UserManager.createDBFriendItem(tmpUser, "attt_me")  #构建格式{uid:{"uid":1, "nickname":"xxx", "level":2, "yellow_level":2, "col":""}}
        	self.m_map_attt_me[str(tmpUID)] = tmpInfo.get(tmpUID)
        	
        	if self.isInMyAtttListUID(tmpUID):  #对方同时在 我关注的列表, 则进入我的好友列表
        		self.insertMyFriendMap(tmpUser)
		
    def delAtttMe(self, uid):
        util.deleteFromList(self.m_list_attt_me_uid, uid)
        util.deleteFromDict(self.m_map_attt_me, str(uid))
    
    def isInAtttMeListUID(self, uid):
        '''uid是否在关注我的队列'''
        return uid in self.m_list_attt_me_uid
		
    def getAtttMeListSize(self):
        return len(self.m_list_attt_me_uid)

    #---#我的好友列表--(我的关注和关注我的队列里都有的id 就是好友)-----------------------------------------
    def setMyFriendMap(self, tmpMap):
    	self.m_map_my_friend = tmpMap
        del self.m_list_my_friend_uid[0:]
        for tmpUID in self.m_map_my_friend.keys():
            util.inserList(self.m_list_my_friend_uid, int(tmpUID))
			
    def getMyFriendMap(self):
    	return self.m_map_my_friend
				
    def insertMyFriendMap(self, tmpUser):
    	'''加入我好友的列表'''
    	if not tmpUser:
    		return
    	tmpUID = tmpUser.getUID()
    	if util.inserList(self.m_list_my_friend_uid, tmpUID):
            tmpInfo = UserManager.createDBFriendItem(tmpUser, "my_friend")  #构建格式{uid:{"uid":1, "nickname":"xxx", "level":2, "yellow_level":2, "col":""}}
            self.m_map_my_friend[str(tmpUID)] = tmpInfo.get(tmpUID)
	    
    def delMyFriend(self, uid):
        util.deleteFromList(self.m_list_my_friend_uid, uid)
        util.deleteFromDict(self.m_map_my_friend, str(uid))
                
    def getMyFriendListUID(self):
        return self.m_list_my_friend_uid[0:]

    def getMyFriendListSize(self):
        return self.getMyAtttListSize()
        #return len(self.m_list_my_friend_uid)
        
    def delMyFriendExt(self, uid):
        '''从我的好友, 我关注列表, 关注我的列表, 暗恋, 被暗恋列表中删除'''
        self.delMyFriend(uid)
        self.delMyAttt(uid)
        self.delAtttMe(uid)
        self.delMyHiddenLove(uid)
        self.delHiddenLoveMe(uid)
    
    def isInMyListExt(self, uid):
        '''是否在我的关注,被关注, 暗恋, 被暗恋列表'''
        if self.isInMyAtttListUID(uid):
            return "my_attt"
        elif self.isInMyHiddenLoveListUID(uid):
            return "my_hidden_love"
        elif self.isInAtttMeListUID(uid):
            return "attt_me"
        elif self.isInHiddenLoveMeListUID(uid):
            return "hidden_love_me"
        else:
            return None
        
        
    #---#我的暗恋列表-------------------------------------------
    def getMyHiddenLoveListUID(self):
		return self.m_list_my_hidden_love_uid[0:]
		
    def setMyHiddenLoveMap(self, tmpMap):
        self.m_map_my_hidden_love = tmpMap
        del self.m_list_my_hidden_love_uid[0:]
        for tmpUID in self.m_map_my_hidden_love.keys():
            util.inserList(self.m_list_my_hidden_love_uid, int(tmpUID))
			
    def getMyHiddenLoveMap(self):
    	return self.m_map_my_hidden_love

    def insertMyHiddenLoveMap(self, tmpUser):
    	'''加入我暗恋的列表'''
    	if not tmpUser:
    		return 0
    	tmpUID = tmpUser.getUID()
    	if util.inserList(self.m_list_my_hidden_love_uid, tmpUID):
    		tmpInfo = UserManager.createDBFriendItem(tmpUser, "my_hidden_love")  #构建格式{uid:{"uid":1, "nickname":"xxx", "level":2, "yellow_level":2, "col":""}}
    		self.m_map_my_hidden_love[str(tmpUID)] = tmpInfo.get(tmpUID)
    		return 1
    	return 0   
    
    def delMyHiddenLove(self, uid):   
        util.deleteFromList(self.m_list_my_hidden_love_uid, uid)
        util.deleteFromDict(self.m_map_my_hidden_love, str(uid))
    
    def isInMyHiddenLoveListUID(self, uid):
    	'''uid是否在我的暗恋队列'''
    	return uid in self.m_list_my_hidden_love_uid
		
    def getMyHiddenLoveListSize(self):
        return len(self.m_list_my_hidden_love_uid)
    
    def getFriendType(self, otherUID):
        '''获取otherUID跟我的关系, “default”:陌生人  “my_attt” 我关注的,  “attt_me”:关注我的, 
                “my_hidden_love”: 我暗恋的,  ”hidden_love_me”: 暗恋我的'''
                
        if otherUID in self.getMyAtttListUID():
            return "my_attt"
        elif otherUID in self.getMyHiddenLoveListUID():
            return "my_hidden_love"
        elif otherUID in self.getAtttMeListUID():
            return "attt_me"
        elif otherUID in self.getHiddenLoveMeListUID():
            return "hidden_love_me"
        else:
            return "default"
                                            
    
	#---#暗恋我的列表-------------------------------------------
    def getHiddenLoveMeListUID(self):
		return self.m_list_hidden_love_me_uid[0:]

    def getHiddenLoveMeMap(self):
        return self.m_map_hidden_love_me
						
    def setHiddenLoveMeMap(self, tmpMap):
        self.m_map_hidden_love_me = tmpMap
        del self.m_list_hidden_love_me_uid[0:]
        for tmpUID in self.m_map_hidden_love_me.keys():
        	util.inserList(self.m_list_hidden_love_me_uid, int(tmpUID))

    def insertHiddenLoveMeMap(self, tmpUser):
        '''加入关注我的列表, 如果对方同时在 我关注的列表, 则进入我的好友列表'''
        if not tmpUser:
        	return
        tmpUID = tmpUser.getUID()
        if util.inserList(self.m_list_hidden_love_me_uid, tmpUID):
        	tmpInfo = UserManager.createDBFriendItem(tmpUser, "hidden_love_me")  #构建格式{uid:{"uid":1, "nickname":"xxx", "level":2, "yellow_level":2, "col":""}}
        	self.m_map_hidden_love_me[str(tmpUID)] = tmpInfo.get(tmpUID)
		
    def delHiddenLoveMe(self, uid):
        util.deleteFromList(self.m_list_hidden_love_me_uid, uid)
        util.deleteFromDict(self.m_map_hidden_love_me, str(uid))
    
    def isInHiddenLoveMeListUID(self, uid):
        '''uid是否在暗恋我的队列'''
        return uid in self.m_list_hidden_love_me_uid
		
    def getHiddenLoveMeListSize(self):
        return len(self.m_list_hidden_love_me_uid)

    #----我的邻居----------
    def getMyNeighbor(self):
        return self.getUserInfoToList("my_neighbor")
    
    def setMyNeighbor(self, tmpList):
        tmpObj = self.getUserInfoObj()
        if tmpObj:
            tmpObj["my_neighbor"] = tmpList


class UserManager(util.SingleClass):
    ''''''
    
    #---- map----    
    s_map_user = {}             #在线用户列表-                {socket_id, user}
    s_map_user_by_uid = {}      #在线用户列表-按user_id排列         {user_id, user}
    s_map_user_blacklist = {}   #全局黑名单 user_id
    
    s_list_boy = []             #男 UID
    s_list_girl = []            #女 UID
    
    s_map_user_leave = {}       #离线用户 user_id
    s_map_user_catch = {}       #缓存用户 user_id
    
    s_timer_id_heartBeat = 0    #心跳定时器
    s_map_hearBeat = {}         #心跳map {时间模， {uid:上次发送时间}}
    
    s_timer_id_log_online = 0    #统计在线人数定时器
   
    
    #---心跳定时器------------------------ 
    @staticmethod
    def insertMapHearBeat(iMod, uid): 
        '''插入心跳map'''
        tmpMap = UserManager.s_map_hearBeat.get(iMod)
        if tmpMap:
            tmpMap[uid] = int(time.time())
        else:
            tmpMap = {}
            tmpMap[uid] = int(time.time())
            UserManager.s_map_hearBeat[iMod] = tmpMap
            
    @staticmethod
    def editMapHearBeatTime(request):
        '''修改心跳map对应用户的 上次发送时间 为当前时间''' 
        if request: 
            tmpUser = UserManager.get_user_by_request(request)
            if tmpUser:
                iMod = tmpUser.m_loginTimeHeartBeatMod
                tmpMap = UserManager.s_map_hearBeat.get(iMod)
                if tmpMap:
                    tmpMap[tmpUser.getUID()] = int(time.time())
        
    @staticmethod
    def _timerHeartBeatFunc(): 
        tmpSendMsgUtil = util.SendMsgUtil(None)
        cmd = "sys_heart_beat"
        tmpTimeMod = int(time.time()) % 60 
        tmpTotal = 0
        tmpSendCount = 0
        
        tmpMap = UserManager.s_map_hearBeat.get(tmpTimeMod)
        if tmpMap:  
            tmpTotal = len(tmpMap)              #总数量
            tmpCurrentSecond = int(time.time()) #当前时间
            tmpTimeNotResponse = const.Config_HeartBeatTime_NotResponse()  #超过一定时间没响应, 则发心跳
            
            for uid, tmpSecond in tmpMap.items():
                tmpUser = UserManager.get_user_by_uid(uid) #用户不在线, 从map删除
                if not tmpUser:
                    tmpMap.pop(uid)       
                    log.print_warning(logger, "_timerHeartBeatFunc, uid[%s] not exists........... " % uid)
                    continue
                if (tmpCurrentSecond - tmpSecond) >= tmpTimeNotResponse:    #超过一定时间没响应, 则发心跳
                    tmpSendMsgUtil.send(cmd, tmpUser.getRequest())
                    tmpSendCount += 1
                
        log.print_debug(logger, "_timerHeartBeatFunc, total[%s], send[%s], tmpTimeMod[%s]" % (tmpTotal, tmpSendCount, tmpTimeMod))
   
    @staticmethod
    def startTimerHeartBeat():
        '''开启心跳定时器''' 
        UserManager.stopTimerHeartBeat()
        mstime = const.Config_HeartBeatTime()    #心跳时间
        UserManager.s_timer_id_heartBeat = util.TimerManager.instance().add_timer(UserManager._timerHeartBeatFunc, mstime, -1)  
        log.print_debug(logger, "UserManager startTimerHeartBeat, timer_id:[%s], mstime[%s]" % (UserManager.s_timer_id_heartBeat, mstime))
    
    @staticmethod
    def stopTimerHeartBeat():
        '''关闭心跳定时器'''
        if UserManager.s_timer_id_heartBeat > 0:
            log.print_debug(logger, "UserManager stopTimerHeartBeat, timer_id:[%s] " % UserManager.s_timer_id_heartBeat)
            util.TimerManager.instance().delete(UserManager.s_timer_id_heartBeat)
            UserManager.s_timer_id_heartBeat = 0
   
   
    #----统计在线人数定时器-------------
    @staticmethod
    def _timerLogOnlineFunc():
        #统计在线人数
        count = len(UserManager.s_map_user) 
        count_boy = len(UserManager.s_list_boy)
        count_girl = len(UserManager.s_list_girl)
        
        #-女孩数量不对的bug--
        if (count_boy + count_girl) != count: 
            log.print_debug(logger, "UserManager _timerLogOnlineFunc exec----test--(count_boy + count_girl) != count-, count[%s], count_boy[%s], count_girl[%s]" % (count, count_boy, count_girl))
            count_girl = count - count_boy

        #--统计酒吧人数
        from bar_order import BarOrderManager
        bar_count = len(BarOrderManager.s_map_user)
        bar_count_boy = len(BarOrderManager.s_list_bar_single_boy)
        bar_count_girl = len(BarOrderManager.s_list_bar_single_girl)
        bar_count_room = len(BarOrderManager.s_map_bar_room)
        
        log.print_debug(logger, "UserManager _timerLogOnlineFunc exec, count[%s], bar_count[%s]" % (count, bar_count))

        tmpStrSql = "insert into t_log_online(count, count_boy, count_girl, bar_count, bar_count_boy, bar_count_girl, bar_count_room, timeline) values('%s', '%s', '%s', '%s', \
        '%s', '%s', '%s', now())" % (count, count_boy, count_girl, bar_count, bar_count_boy, bar_count_girl, bar_count_room) 
        #conn = mysqlHelper.mysql()
        #conn.query(tmpStrSql)
        util.SqlThread.addSqlStr(tmpStrSql) #线程写记录
        
    @staticmethod
    def startTimerLogOnline():
        '''开启统计在线人数定时器''' 
        UserManager.stopTimerLogOnline()
        mstime = const.Config_login_online_time()    #时间
        UserManager.s_timer_id_log_online = util.TimerManager.instance().add_timer(UserManager._timerLogOnlineFunc, mstime, -1)  
        log.print_debug(logger, "UserManager startTimerLogLogin, timer_id:[%s], mstime[%s]" % (UserManager.s_timer_id_log_online, mstime))
    
    @staticmethod
    def stopTimerLogOnline():
        '''关闭统计在线人数定时器'''
        if UserManager.s_timer_id_log_online > 0:
            log.print_debug(logger, "UserManager stopTimerLogLogin, timer_id:[%s] " % UserManager.s_timer_id_log_online)
            util.TimerManager.instance().delete(UserManager.s_timer_id_log_online)
            UserManager.s_timer_id_log_online = 0
   
   
   
    
    #给所有用户群发消息 cmd="reload_data" ,res="reload_data" ,back="data",backmsg={"cloth":"http://www.baidu.com/"} user=[1001,1002"]
    @staticmethod
    def sendmsg_to_any(request,cmd,res,back,backmsg,user='all'):        
        if not UserManager.s_map_user_by_uid:
            return False
        
        tmpSendMsgUtil = util.SendMsgUtil(request)
        tmpSendMsgUtil.update_res(res)
        tmpSendMsgUtil.add_item(back,backmsg)        
        tmpMsg = tmpSendMsgUtil.getEncodeContent()
        
        if user=='all':
            for k,v in UserManager.s_map_user_by_uid.iteritems():
                tmpSendMsgUtil.send(cmd=cmd,request=v.m_request,msg=tmpMsg)
        else:
            for k in user:
                tmpUser = UserManager.get_user_by_uid(k)
                if tmpUser:
                    tmpSendMsgUtil.send(cmd=cmd,request=tmpUser.m_request,msg=tmpMsg)
        return True
    
    @staticmethod
    def sendMsgToAll(cmd, msg):
        '''发送消息给所有在线用户'''  
        tmpSendMsgUtil = util.SendMsgUtil(None)           
        for tmpUID, tmpUser in UserManager.s_map_user_by_uid.iteritems():
            if tmpUser:
                tmpSendMsgUtil.send(cmd=cmd,request=tmpUser.m_request,msg=msg)

    @staticmethod
    def sendMsgToAllExt(cmd, tmpSendMsgUtil):
        '''发送消息给所有在线用户'''
        tmpMsg = tmpSendMsgUtil.getEncodeContent()     
        for tmpUID, tmpUser in UserManager.s_map_user_by_uid.iteritems():
            if tmpUser:
                tmpSendMsgUtil.send(cmd=cmd, request=tmpUser.m_request, msg=tmpMsg)

    @staticmethod 
    def pushSysInfoToAll(tmpType, tmpContent, tmpContentAddtion):
        '''给所有在线用户push系统广播,  消息类型, 消息内容, 内容附加'''
        cmd = "sys_info"  
        tmpSendMsgUtil = util.SendMsgUtil(None)  
        
        tmpSendMsgUtil.add_item("type", tmpType)                        #消息类型
        tmpSendMsgUtil.add_item("content", tmpContent)                  #消息内容
        tmpSendMsgUtil.add_item("content_addition", tmpContentAddtion)  #内容附加        
        tmpMsg = tmpSendMsgUtil.getEncodeContent()                      #消息体编码
        
        for tmpUID, tmpUser in UserManager.s_map_user_by_uid.iteritems():
            if tmpUser:
                tmpSendMsgUtil.send(cmd=cmd,request=tmpUser.m_request,msg=tmpMsg)

    @staticmethod 
    def pushSysInfoToSomebody(tmpType, tmpContent, tmpContentAddtion, *tmpUIDTuple):
        '''给某些用户push系统广播,  消息类型, 消息内容, 内容附加'''
        if not isinstance(tmpUIDTuple, tuple) or not len(tmpUIDTuple):
            return
        cmd = "sys_info"  
        tmpSendMsgUtil = util.SendMsgUtil(None)  
        
        tmpSendMsgUtil.add_item("type", tmpType)                        #消息类型
        tmpSendMsgUtil.add_item("content", tmpContent)                  #消息内容
        tmpSendMsgUtil.add_item("content_addition", tmpContentAddtion)  #内容附加        
        tmpMsg = tmpSendMsgUtil.getEncodeContent()                      #消息体编码
        
        for tmpUID in tmpUIDTuple:
            tmpUser = UserManager.get_user_by_uid(tmpUID)
            if tmpUser:
                tmpSendMsgUtil.send(cmd=cmd,request=tmpUser.m_request,msg=tmpMsg) 

    @staticmethod 
    def pushBasicSysInfo(tmpContent, uid):
        '''给某人push基本系统消息, (内容, 用户ID)'''
        tmpType = "sys_info"
        UserManager.pushSysInfoToSomebody(tmpType, tmpContent, None, uid)
        
    @staticmethod
    def kill_user_after_clear_info(tmpUser, bCloseRequest=False): 
        '''踢用户， 清理用户信息'''
        if tmpUser:
            import bar_order
            import process_user
            uid = tmpUser.getUID()
            socket_id = tmpUser.getSocketID()
            request = tmpUser.getRequest()
            
            log.print_debug(logger, "UserManager kill_user_after_clear_info exec, uid[%s], kill socket_id[%s] " % (uid, socket_id))
            
            import bar_order
            bar_order.BarOrderManager.instance().leaveBarOrder(request, tmpUser, bClose=True) #用户掉线,处理退出酒吧名人堂等
            UserManager.notice_friends(tmpUser, 'logout')        #通知好友， 用户退出
            
            #--用户下线， 则把-我的关注， 关注我的，我的好友-写DB--
            UserManager.updateDBUserMyAtttAndMyFriendAndAtttMe(tmpUser)
            
            import task
            task.taskManager.save_task_to_db(tmpUser)
            
            #process_user.method_sys_logout(request, tmpUser)
            UserManager.add_user_leave(uid)
            UserManager.add_user_log_login(request, uid)    
            UserManager.del_user_Ext(socket_id, uid, tmpUser.getSex())
            
            if bCloseRequest and request:
                request.close()             #关闭用户socket连接

    @staticmethod
    def kill_user_after_clear_info_Ext(uid, bCloseRequest=False): 
        '''踢用户， 清理用户信息'''
        tmpUser = UserManager.s_map_user_by_uid.get(uid)
        UserManager.kill_user_after_clear_info(tmpUser, bCloseRequest)

    @staticmethod
    def kill_user(uid):
        '''关闭用户连接'''        
        tmpPreUser = UserManager.s_map_user_by_uid.get(uid)
        if tmpPreUser:   
            tmpPreUser.getRequest().close() #关闭用户socket连接
            
    
    #用户登录后初始化用户信息
    @staticmethod
    def add_user(userinfo, request): 
        socket_id = request.socket_id
        uid = userinfo["uid"]  
        tmpUser = UserManager.s_map_user.get(socket_id)
        
        if tmpUser is None:           
            tmpUser = User(socket_id, userinfo, request, bLogin=True) #新建用户
                       
            UserManager.s_map_user[socket_id] = tmpUser
            UserManager.s_map_user_by_uid[uid] = tmpUser
            
            tmpList = UserManager.s_list_boy            #插入队列
            if tmpUser.getSex() == 0:
                tmpList = UserManager.s_list_girl
            util.inserList(tmpList, uid)
        else:   
            log.print_warning(logger, "UserManager add_user exec, uid[%s], socket_id[%s] exists..." % (uid, socket_id))
        return tmpUser
    
    #用户离开后添加到离线队列
    @staticmethod
    def add_user_leave(uid):       
        #UserManager.s_map_user_leave[uid]=UserManager.get_user_by_uid(uid)        
        return True
   
    #设置用户的位置
    @staticmethod
    def set_user_palce(request, place):
        user = UserManager.get_user_by_request(request)
        if not user:
            return None
        user.m_current_place = place        
        return True
    
    #设置用户当前位置
    @staticmethod
    def set_user_place_by_uid(uid,place):
        user = UserManager.get_user_by_uid(uid)
        if not user:
            return None
        user.m_current_place = place        
        return True
    
    #得到当前用户的位置
    @staticmethod
    def get_user_place(request):
        user = UserManager.get_user_by_request(request)
        if not user:
            return None
        return user.m_current_place 

    @staticmethod
    def update_user(uid, userinfo, add=None): 
        '''更新用户基本资料到缓存'''     
        tmpUser = UserManager.s_map_user_by_uid.get(uid)
        if not tmpUser:
            return False 
        if not add:
            for k, v in userinfo.iteritems(): 
                tmpUser.m_userinfo[k] = v
        else:
            for k, v in userinfo.iteritems(): 
                tmpVal = tmpUser.getUserInfoToInt(k)
                tmpUser.m_userinfo[k] = tmpVal + v
        return True
    
    #设置用户关注用户      type=set 表示增加或修改  type=del表示删除
    @staticmethod
    def set_user_attention(request, to_uid, set_type='set'): 
        
        tUser = UserManager.get_user_by_request(request)      
        if not tUser:
            return {'res':'user_is_null'}
        uid = tUser.m_userinfo['uid']
        
        #查询我的关注信息
        tmpUser = UserManager.get_userinfo_by_col(uid, 'a.uid,a.nickname,b.yellow_level,c.my_attt,my_friend,c.attt_me')     
        nickname = tmpUser['nickname']
        #查询被关注用户的 我的关注信息
        touser = UserManager.get_userinfo_by_col(to_uid, 'a.uid,a.nickname,b.yellow_level,c.my_attt,my_friend,c.attt_me')
        if not touser:            
            return {'res':'user_is_null'}       
        to_nickname = touser['nickname']
        if touser['my_attt']:
            to_user_my_attt = json_decode(touser['my_attt'])
        else:
            to_user_my_attt = []
        if tmpUser['my_attt']:                    
            my_att = json_decode(tmpUser['my_attt'])
            if my_att:
                pass
                #if len(my_att)>=tUser.getEnergy() and set_type=='set':
                #    return {'res':'not_energy'}
            else:
                 my_att = []
        else:
            my_att = []
        
        #初始化我的关注记录    
        my_rec = {"uid":to_uid, "nickname":to_nickname, "yellow_level":touser['yellow_level']}
        #初始化对方关注记录
        to_rec = {"uid":uid, "nickname":nickname, "yellow_level":tmpUser['yellow_level']}
        tmpType = 0  #关注类型0为普通关注1为双方关注
        
        #如果已经关注了则直接返回成功
        if my_rec not in my_att:       
            my_att.append(my_rec)
        else:
            if set_type=='set':
                return {"res":True,"type":tmpType, "user":to_rec}
                
        if touser['attt_me']:            
            to_user_att_me = json_decode(touser['attt_me'])
        else:
            to_user_att_me = []
            
        if to_rec not in to_user_att_me:
            to_user_att_me.append(to_rec)
               
        if set_type == 'del':
            if my_rec in my_att:
                my_att.remove(my_rec)
            if to_rec in to_user_att_me:
                to_user_att_me.remove(to_rec)
        #更新数据表    
        conn = mysqlHelper.mysql()        
        #更新我的关注对象
        conn.upData('t_user_record', {"my_attt":json_encode(my_att),'my_friend':json_encode(my_att)}, "WHERE uid = '%d'" % uid,asyn=True)
        #更新对方的被关注对象
        conn.upData('t_user_record', {"attt_me":json_encode(to_user_att_me)}, "WHERE uid = '%d'" % to_uid,asyn=True)       
        conn.upData('t_user_data', {"count_att":1}, "WHERE uid = %d" % to_uid, 1)
        
        #util.CountUserUtil.judgeAndEditExt('set_attention', request, uid, "att")
        #util.CountUserUtil.judgeAndEditExt('set_attention', None, to_uid, "atted") 
             
        if to_rec in to_user_my_attt :
            tmpType = 1
            UserManager.set_user_friend(tmpUser, touser, set_type)  
        if set_type == 'set':    
            #发一条系统消息通知对方
            tmpSendType = "add_attention"
            tmpContent = "%s关注了你" %nickname               
            tmpContentAddtion = {"yellow_level": tmpUser.get('yellow_level'), "nickname": nickname, "uid": uid}           
            UserManager.pushSysInfoToSomebody(tmpSendType, tmpContent, tmpContentAddtion, *tuple([to_uid]))    
        return {"res":True,"type":tmpType, "user":to_rec}
    
    #设置两个用户为好友  type=set 表示增加或修改  type=del表示删除
    @staticmethod
    def set_user_friend(user, touser, set_type='set'):
        return
        uid = user['uid']
        nickname = user['nickname']  
        #查询被关注用户的 我的关注信息
        to_uid = touser['uid']
        to_nickname = touser['nickname']
        if user['my_friend']:
            myfriend = json_decode(user['my_friend'])
        else:
            myfriend = []
        if touser['my_friend']: 
            to_user_myfriend = json_decode(touser['my_friend'])
        else:
            to_user_myfriend = []
        
        my_rec = {"uid":to_uid, "nickname":to_nickname, "yellow_level":touser['yellow_level']}
        to_rec = {"uid":uid, "nickname":nickname, "yellow_level":user['yellow_level']}
        
       
        if my_rec not in  myfriend:
            myfriend.append(my_rec)
       
        if to_rec not in to_user_myfriend:
            to_user_myfriend.append(to_rec)
        
        if set_type == 'del':
            myfriend.remove(my_rec)
            to_user_myfriend.remove(to_rec)
        #更新数据表
        conn = mysqlHelper.mysql()
        #把我放在对方的好友列表中
        conn.upData('t_user_record', {"my_friend":json_encode(myfriend)}, "WHERE uid = '%d'" % uid,asyn=True)      
        #把对方放到我的好友列表中
        conn.upData('t_user_record', {"my_friend":json_encode(to_user_myfriend)}, "WHERE uid = '%d'" % to_uid,asyn=True)       
        return True
    
    #操作黑名单
    @staticmethod
    def set_to_black_list(request, to_uid, set_type='set'):
        user = UserManager.get_user_by_request(request)      
        if not user:
            return None
        uid = user.m_userinfo['uid']
        touser = UserManager.get_userinfo_by_col(to_uid, 'a.nickname')
        to_nickname = touser['nickname']
        
        user = UserManager.get_userinfo_record(uid, 'nickname,my_blacklist')
        if user['my_blacklist']:
            black_list = json_decode(user['my_blacklist'])
        else :
            black_list = []
        
        if {"uid":to_uid, "nickname":to_nickname} not in black_list:
            black_list.append({"uid":to_uid, "nickname":to_nickname})
        if set_type == 'del':
            black_list.remove({"uid":to_uid, "nickname":to_nickname})
         #更新数据表
        conn = mysqlHelper.mysql()
        #把对方放到我的黑名单列表中
        conn.upData('t_user_record', {"my_blacklist":json_encode(black_list)}, "WHERE uid = '%d'" % uid,asyn=True)  
        return True
    
    #用户退出用户后从列队里清空
    @staticmethod
    def del_user(request=None, socket_id=None, uid=None, return_uid=None, return_socket_id=None):      
        if request: 
#            for v in request.__dict__:
#                print  v            
            socket_id = request.socket_id                            
        if socket_id == None or uid == None:                   
            if socket_id and uid == None:
                uid = UserManager.get_user(socket_id).m_userinfo['uid']
            if socket_id == None and uid:
                socket_id = UserManager.get_user_by_uid(uid).m_socket_id   
          
        UserManager.s_map_user.pop(socket_id)
        UserManager.s_map_user_by_uid.pop(uid)
#        del UserManager.s_map_user[socket_id]
#        del UserManager.s_map_user_by_uid[uid]
        if return_uid and return_socket_id:
            return {"uid":uid, "socket_id":socket_id}
        if return_uid:
            return uid
        if return_socket_id:
            return socket_id
        return True
    
        
    @staticmethod
    def del_user_Ext(socket_id, uid, sex):
        '''用户退出用户后从列队里清空'''
        util.deleteFromDict(UserManager.s_map_user, socket_id)
        util.deleteFromDict(UserManager.s_map_user_by_uid, uid)
        
        tmpList = UserManager.s_list_boy            #队列删除
        if sex == 0:
            tmpList = UserManager.s_list_girl
        util.deleteFromList(tmpList, uid)

    
    #根据socket_id获取用户信息
    @staticmethod
    def get_user(socket_id):
        return UserManager.s_map_user.get(socket_id)
    
    #根据UID获取用户信息
    @staticmethod
    def get_user_by_uid(uid):
        return UserManager.s_map_user_by_uid.get(uid)

    #获取用户对象, 对象不存在, 则发错误信息
    @staticmethod
    def getUserExt(cmd, tmpSendMsgUtil, socket_id):
        '''参数:(命令字, 发送器，socket_id)'''
        tmpOwnerUser = UserManager.get_user(socket_id) #用户对象    
        if tmpOwnerUser is None:
            log.print_warning(logger, "UserManager getUserExt exec, user_is_null_owner, sockID:%s" % socket_id) 
            tmpSendMsgUtil.update_res("user_is_null_owner")     
            tmpSendMsgUtil.send(cmd) 
        return tmpOwnerUser
    
    #获取用户对象, 对象不存在, 则发错误信息
    @staticmethod
    def getUserByUIDExt(cmd, tmpSendMsgUtil, uid):
        '''参数:(命令字, 发送器，socket_id)'''
        tmpOwnerUser = UserManager.get_user_by_uid(uid) #用户对象    
        if tmpOwnerUser is None:
            log.print_warning(logger, "UserManager getUserByUIDExt exec, user:[%s] is null" % uid) 
            tmpSendMsgUtil.update_res("user_is_null")     
            tmpSendMsgUtil.send(cmd) 
        return tmpOwnerUser
    
    #根据请求获取用户信息
    @staticmethod
    def get_user_by_request(request): 
        if request is None:
            return None
        socket_id = request.socket_id
        return UserManager.s_map_user.get(socket_id)   
    #获取在线用户ID
         
    @staticmethod
    def get_online_user_list(tmpSex):         
        tmpList = UserManager.s_list_boy   
        if tmpSex == 0:
            tmpList = UserManager.s_list_girl
        return tmpList[0:]
     
    @staticmethod
    def get_userinfo(uid, bAllInfo=True, bGetUser=False):
        '''获取用户(user和user_data 表)的所有记录''' 
        tmpUser = UserManager.get_user_by_uid(uid);
        
        if tmpUser is None: #用户不存在, 则查DB
            sql = "SELECT a.*, b.*  FROM  t_user a, t_user_data b WHERE a.uid=b.uid AND a.uid = %d" % uid
            conn = mysqlHelper.mysql()
            info = conn.getRow(sql)
            if not info:
                log.print_warning(logger, "UserManager get_userinfo exec fail, uid[%s] not exist..." % uid)
                return {}
            
            del info['b.uid']
            del info['b.nickname'] 
            
            from util import *
            
            tmpInfoArray = ['my_clothing', 'my_ornament', 'my_present', 'my_furniture', 'my_props', 'my_props_using', 'my_bodyinfo', 'remark_info']
            util.jsonDecodePerListItemToDict(info, tmpInfoArray) #把数组info的 项 在数组tmpInfoArray的字段 转换成 字典对象
        
            tmpInfoArray = ['reg_step']
            util.jsonDecodePerListItemToList(info, tmpInfoArray) #把数组info的 项 在数组tmpInfoArray的字段 转换成 数组对象
        
            tmpInfoArray = ['birthday', 'regtime', 'last_login_time', 'upload_head_time']
            util.setPerListItemToStr(info, tmpInfoArray)   #把数组info的 项 在数组tmpInfoArray的字段 转换成 字符串
             
            tmpUser = User(0, info, None) #新建一临时用户  
        
        if bGetUser:
            return tmpUser
			
        from bar_order import BarOrderManager
        if bAllInfo:
            return BarOrderManager.instance().getUserInfoToClientForLogin(tmpUser) #返回用户信息
        else:
            return BarOrderManager.instance().getUserInfoToClient(tmpUser) #返回用户信息
    
    #'''根据UID获取用户对象'''
    @staticmethod
    def getUserObjByUID(tmpReqUID):
        bTargetUserOnline = 1  #目标用户是否在线, 0:不在线, 1:在线
        tmpTargetUser = UserManager.get_user_by_uid(tmpReqUID) #用户对象  
        if tmpTargetUser is None: 
            from hall_of_fame import HallOfFameManager
            tmpTargetUser = HallOfFameManager.instance().queryUserFromDB(tmpReqUID)
            bTargetUserOnline = 0
        return bTargetUserOnline, tmpTargetUser
    
    #获取用户指定列信息   user  user_data user_record
    #get_userinfo_by_col('123,456,789','nickname,age,pwd')
    @staticmethod 
    def get_userinfo_by_col(uids, col):
        conn = mysqlHelper.mysql()
        sql = "SELECT %s FROM t_user a \
        , t_user_data b   \
        , t_user_record c   \
        WHERE a.uid=b.uid AND a.uid=c.uid  AND a.uid in ( %s )" % (col, uids)       
        info = conn.getAll(sql)         
        if len(info) == 1:
            return info[0]
        else:
            return info
        
    @staticmethod 
    def get_user_basic_info(uid, col=None):
        '''从数据库获取用户基本信息'''
        conn = mysqlHelper.mysql()
        if not col:
            sql = "SELECT * FROM t_user WHERE uid = '%d' " % uid
        else:
             sql = "SELECT %s FROM t_user WHERE uid = '%d' " % (col, uid)

        info = conn.getRow(sql)
        if not info:
            return {}         
            
        tmpInfoArray = ['reg_step']
        util.jsonDecodePerListItemToList(info, tmpInfoArray) #字符串转换成json队列对象 
            
        tmpInfoArray = ['birthday', 'regtime', 'upload_head_time']
        util.setPerListItemToStr(info, tmpInfoArray) #转换字符串对象
            
        info['age'] = UserManager.countAge(info['birthday'])
        return info
    
    #获取用户游戏资料    
    @staticmethod
    def get_user_game_info(uid, col=None):
        tmpUser = UserManager.get_user_by_uid(uid);
        if tmpUser:
            from bar_order import BarOrderManager
            return BarOrderManager.instance().getUserInfoToClient(tmpUser)
        else:
            if not col:
                sql = "SELECT `uid`, `nickname`, `level`,`exp`, `charm`, `courage`, `power`,`energy`,\
                `quality`, `assets`,`gold`, `money`, courage_time, power_time, quality_time,`count_att`, `count_room`, `yellow_level`,\
                `yellow_vip`, `get_yellow_reg_gift`, `get_yellow_day_gift`, \
                `see_yellow_gift`,`cloth_charm` FROM t_user_data WHERE uid = '%d'" % uid
            else:
                sql = "SELECT %s FROM t_user_data WHERE uid = '%d'" % (col, uid)
            #print sql
            conn = mysqlHelper.mysql()
            info = conn.getRow(sql)
            return info
    
    #获取用户穿着信息
    @staticmethod
    def get_user_wear_info(uid, col=None):
        conn = mysqlHelper.mysql()
        if not col:
            sql = "SELECT `uid`,`nickname`,`my_clothing`, `my_ornament`,`my_present`, `my_furniture`, `my_props`, `my_bodyinfo`, `cloth_charm` \
            FROM t_user_data WHERE uid = '%d'" % uid
        else:
            sql = "SELECT %s FROM t_user_data WHERE uid = '%d'" % (col, uid)
        return conn.getRow(sql)
    
    #获取用户记录信息
    @staticmethod
    def get_userinfo_record(uid, col):
        conn = mysqlHelper.mysql()
        sql = "SELECT %s FROM t_user_record WHERE uid = '%d'" % (col, int(uid))        
        return conn.getRow(sql)
    
    @staticmethod
    def get_userinfo_friend_fromDB(uid):
        '''获取好友列表，我关注的人列表，关注我的人列表'''
        conn = mysqlHelper.mysql()
        sql = "SELECT uid, nickname, my_friend, my_attt, attt_me, hidden_love_me, my_hidden_love, my_neighbor FROM t_user_record WHERE uid = %s" % uid
        info = conn.getRow(sql)
        if not info:
            return {}
        
        tmpInfoArray = ["my_friend", "my_attt", "attt_me", "hidden_love_me", "my_hidden_love"]
        util.jsonDecodePerListItemToDict(info, tmpInfoArray) #字符串转换成json对象 
        
        tmpInfoArray3 = ['my_neighbor']
        util.jsonDecodePerListItemToList(info, tmpInfoArray3) #把数组info的 项 在数组tmpInfoArray的字段 转换成 数组对象
        return info

    @staticmethod
    def setUserFriendMapExt(tmpUser, tmpInfo):
        '''把关注, 被关注, 暗恋, 被暗恋 更新到用户对象'''
        tmpUser.setMyFriendMap(tmpInfo.get("my_friend", {})) #存到内存
        tmpUser.setMyAtttMap(tmpInfo.get("my_attt", {}))
        tmpUser.setAtttMeMap(tmpInfo.get("attt_me", {}))
        tmpUser.setMyHiddenLoveMap(tmpInfo.get("my_hidden_love", {}))
        tmpUser.setHiddenLoveMeMap(tmpInfo.get("hidden_love_me", {}))
        
        tmpUser.setMyNeighbor(tmpInfo.get("my_neighbor", []))
        
    @staticmethod
    def updateFriendOnlineInfo(tmpFriendMap): 
    	'''更新在线好友信息，'''
    	for tmpUID, tmpDict in tmpFriendMap.items():
            tmpUID = int(tmpUID)
            tmpUser = UserManager.get_user_by_uid(tmpUID)
            if tmpUser:
            	tmpDict["online"] = 1	#0:不在线, 1:在线
            	tmpDict["nickname"] = tmpUser.getNickname()
            	tmpDict["level"] = tmpUser.getLevel()
            	tmpDict["yellow_level"] = tmpUser.getYellowLevel()
                tmpDict["regfrom"] = tmpUser.getRegfrom()  #注册来源
            else:
            	tmpDict["online"] = 0	#0:不在线, 1:在线
    	return tmpFriendMap
    
    @staticmethod
    def createDBFriendItem(tmpUser, tmpCol, tmpOnline=1):
        '''建立DB（my_friend, my_attt, attt_me)字段格式'''
        tmpReturnDict = {}
        if tmpUser:
            tmpDict = {}
            tmpUID = tmpUser.getUID()
            tmpDict["online"] = tmpOnline     #0:不在线, 1:在线
            tmpDict["uid"] = tmpUID
            tmpDict["nickname"] = tmpUser.getNickname()
            tmpDict["level"] = tmpUser.getLevel()
            tmpDict["yellow_level"] = tmpUser.getYellowLevel()
            tmpDict["col"] = tmpCol   #my_friend, my_attt, attt_me
            tmpDict["regfrom"] = tmpUser.getRegfrom()  #注册来源
            tmpReturnDict[tmpUID] = tmpDict   # { uid:{...} }
        return tmpReturnDict
    
    @staticmethod
    def notice_friends(tmpUser, act='online'):
        '''通知好友我已经上线, 上线把我关注的和关注我的保存到缓存'''
        if tmpUser is None:
            return
        uid = tmpUser.getUID()
        socket_id = tmpUser.getSocketID()
        nickname = tmpUser.getNickname()
        
        log.print_debug(logger, "UserManager notice_friends exec [0].., uid[%s], socket_id[%s], time[%s] " % (uid, socket_id, time.time()))
        
        if act in ["online"]:  #登陆上线, 查询我的关注， 关注我的等信息 存到内存
            tmpInfo = UserManager.get_userinfo_friend_fromDB(uid) 
            UserManager.setUserFriendMapExt(tmpUser, tmpInfo)#存到内存
#            tmpUser.setMyFriendMap(tmpInfo.get("my_friend")) #存到内存
#            tmpUser.setMyAtttMap(tmpInfo.get("my_attt"))
#            tmpUser.setAtttMeMap(tmpInfo.get("attt_me"))
#            tmpUser.setMyHiddenLoveMap(tmpInfo.get("my_hidden_love"))
#            tmpUser.setHiddenLoveMeMap(tmpInfo.get("hidden_love_me"))
       
        tmpOnline = 0 #0:不在线， 1:在线
        tmpContent = ""
             
        if act=='online':
            tmpType = "friend_login"
            tmpContent = '<font color="#ff6600">您的好友 %s 上线了，快去找他聊聊吧</font>' % nickname
            tmpOnline = 1
        else:
            tmpType = "friend_logout"
            tmpContent = '<font color="#ff6600">您的好友 %s 下线了</font>' % nickname  
            tmpOnline = 0   

        #tmp_list_my_attt = tmpUser.getMyAtttListUID()
        tmp_list_attt_me = tmpUser.getAtttMeListUID()

        setAtttMe = set(tmp_list_attt_me)
        setHiddenLoveMe = set(tmpUser.getHiddenLoveMeListUID())
        tmp_list_hidden_love_me = list(setHiddenLoveMe)

#        setMyAttt = set(tmp_list_my_attt)
#        setAtttMe = set(tmpUser.getAtttMeListUID())
#        setMyHiddenLove = set(tmpUser.getMyHiddenLoveListUID())
#        setHiddenLoveMe = set(tmpUser.getHiddenLoveMeListUID())
                
        #--确保一个人只发送一次
#        tmp_list_attt_me = list(setAtttMe & (setAtttMe ^ setMyAttt))
#        tmp_list_my_hidden_love = list(setMyHiddenLove & (setAtttMe ^ setMyAttt ^ setMyHiddenLove))
#        tmp_list_hidden_love_me = list(setHiddenLoveMe & (setAtttMe ^ setMyAttt ^ setMyHiddenLove ^ setHiddenLoveMe))
        
#        #先发我关注的
#        if len(tmp_list_my_attt) > 0:
#            tmpContentAddtion = UserManager.createDBFriendItem(tmpUser, "attt_me", tmpOnline)#构建格式{"uid":1, "nickname":"a", "level":2, "yellow_level":2, "col":""}       
#            UserManager.pushSysInfoToSomebody(tmpType, tmpContent, tmpContentAddtion, *tuple(tmp_list_my_attt)) 
        #再发关注的我
        if len(tmp_list_attt_me) > 0:
            tmpContentAddtion = UserManager.createDBFriendItem(tmpUser, "my_attt", tmpOnline)  #构建格式{"uid":1, "nickname":"a", "level":2, "yellow_level":2, "col":""} 
            UserManager.pushSysInfoToSomebody(tmpType, tmpContent, tmpContentAddtion, *tuple(tmp_list_attt_me))
#        #我暗恋的
#        if len(tmp_list_my_hidden_love) > 0:
#            tmpContentAddtion = UserManager.createDBFriendItem(tmpUser, "hidden_love_me", tmpOnline)#构建格式{"uid":1, "nickname":"a", "level":2, "yellow_level":2, "col":""}       
#            UserManager.pushSysInfoToSomebody(tmpType, tmpContent, tmpContentAddtion, *tuple(tmp_list_my_hidden_love)) 
        #暗恋我的
#        if len(tmp_list_hidden_love_me) > 0:
#            tmpContentAddtion = UserManager.createDBFriendItem(tmpUser, "my_hidden_love", tmpOnline)#构建格式{"uid":1, "nickname":"a", "level":2, "yellow_level":2, "col":""}       
#            UserManager.pushSysInfoToSomebody(tmpType, tmpContent, tmpContentAddtion, *tuple(tmp_list_hidden_love_me)) 

    @staticmethod
    def push_user_login_info(tmpUser):
        '''push用户登陆系统消息'''
        if not tmpUser:
            return
        uid = tmpUser.getUID()
        socket_id = tmpUser.getSocketID()
        log.print_debug(logger, "UserManager push_user_login_info exec [0]..., uid[%s], socket_id[%s], time[%s] " % (uid, socket_id, time.time()))
        
        dayFirstLogin = 0               #是否首次登陆(0:非; 1:首次登陆)
        if tmpUser.isDayFirstLogin():
            dayFirstLogin = 1
            
        tmpType = "user_login_info"
        tmpContent = ""
        tmpContentAddtion = {}    
        tmpContentAddtion["yellow_level"] = tmpUser.getUserInfoToInt("yellow_level")                 #黄钻等级1~7级别，0非黄钻用户
        tmpContentAddtion["yellow_vip"] = tmpUser.getUserInfoToInt("yellow_vip")  	                 #年费黄钻  0不是; 1是
        tmpContentAddtion["get_yellow_reg_gift"] = tmpUser.getUserInfoToInt("get_yellow_reg_gift")   #是否领取黄钻新手礼包  (0:未; 1:已)
        tmpContentAddtion["get_yellow_day_gift"] = tmpUser.getUserInfoToInt("get_yellow_day_gift")   #是否领取黄钻每天礼包  (0:未; 1:已)
        tmpContentAddtion["see_yellow_gift"] = tmpUser.getUserInfoToInt("see_yellow_gift")			 #非黄钻用户是否查看黄钻信息  (0:未; 1:已)
        if dayFirstLogin==1:                                                                         #如果是首次登录，可以领取用户礼包
            tmpUser.m_userinfo['get_day_gift']=0;
            #conn = mysqlHelper.mysql()
            #conn.upData('t_user_data', {'get_day_gift':0}, "WHERE uid = %d" % uid)
        	
        tmpContentAddtion["get_day_gift"] = tmpUser.getUserInfoToInt("get_day_gift") 				 #是否领当日首次礼包  (0:未; 1:已)
        tmpContentAddtion["first_login"] = dayFirstLogin  				                             #是否首次登陆(0:非; 1:首次登陆)
        
        tmpContentAddtion["sys_info"] = const.Config_user_first_login_info()   		#系统信息

        tmp_award_info = {} 
        #--黄钻注册礼包       
        tmpInfo, tmpGold, tmpOther = UserManager.get_config_user_login_info(tmpUser, "yellow_reg")  
        tmp_award_info["yellow_reg_info"] = tmpInfo
        tmp_award_info["yellow_reg_gold"] = tmpGold 			
        tmp_award_info["yellow_reg_other"] = tmpOther
        #--黄钻每日礼包
        tmpInfo, tmpGold, tmpOther = UserManager.get_config_user_login_info(tmpUser, "yellow_day")  
        tmp_award_info["yellow_day_info"] = tmpInfo    
        tmp_award_info["yellow_day_gold"] = tmpGold             
        tmp_award_info["yellow_day_other"] = tmpOther
        #--当日首次礼包
        tmpInfo, tmpGold, tmpOther = UserManager.get_config_user_login_info(tmpUser, "day")   
        tmp_award_info["day_info"] = tmpInfo   
        tmp_award_info["day_gold"] = tmpGold                        
        tmp_award_info["day_other"] = tmpOther
        tmpContentAddtion["award_info"] = tmp_award_info  #奖励信息 
        #--push消息
        UserManager.pushSysInfoToSomebody(tmpType, tmpContent, tmpContentAddtion, uid)

        log.print_debug(logger, "UserManager push_user_login_info exec [1]..., uid[%s], socket_id[%s], time[%s] " % (uid, socket_id, time.time()))

    @staticmethod
    def push_sys_info_homepage_msg(tmpUser):
        '''push首页滚动信息'''
        if not tmpUser:
            return
        uid = tmpUser.getUID()
        socket_id = tmpUser.getSocketID()
        log.print_debug(logger, "UserManager push_sys_info_homepage_msg exec [0]..., uid[%s], socket_id[%s], time[%s] " % (uid, socket_id, time.time()))
           
        tmpType = "sys_info_homepage_msg"
        tmpContent = ""
        tmpContentAddtion = const.Config_sys_info_homepage_msg()   		#滚动信息
        #--push消息
        UserManager.pushSysInfoToSomebody(tmpType, tmpContent, tmpContentAddtion, uid)
        
        log.print_debug(logger, "UserManager push_sys_info_homepage_msg exec [1]..., uid[%s], socket_id[%s], time[%s] " % (uid, socket_id, time.time()))
    
    @staticmethod
    def get_config_user_login_info(tmpUser, typeName):
        '''从配置信息获取相应的礼包信息'''
        if not tmpUser:
            return "", 0, []
        tmpSexStr = "girl"
        if tmpUser.getSex() == 1:
            tmpSexStr = "boy" 
            
        infoName = typeName + "_info_for_" + tmpSexStr      #如"yellow_day_info_for_girl"
        goldName = typeName + "_gold_for_" + tmpSexStr      #如"yellow_day_gold_for_girl"
        otherName = typeName + "_other_for_" + tmpSexStr    #如"yellow_day_other_for_girl"
        
        tmpInfo = const.Config_User_Login_Gift.get(infoName)
        tmpGold = const.Config_User_Login_Gift.get(goldName)
        tmpOther = const.Config_User_Login_Gift.get(otherName)
        
        return tmpInfo, tmpGold, tmpOther[0:]
    
    #用户退出记录日志
    @staticmethod
    def add_user_log_login(request, uid):
        user = UserManager.get_user_by_request(request)
        if not user:
            return False
        
        nickname = user.m_userinfo['nickname']       
        s_time = user.m_logintime
        e_time = time.strftime('%Y-%m-%d %H:%M:%S')      
        st = time.mktime(time.strptime(s_time, '%Y-%m-%d %H:%M:%S'))
        et = time.mktime(time.strptime(e_time, '%Y-%m-%d %H:%M:%S'))       
        sumtime = et - st   
         
        conn = mysqlHelper.mysql() 
        sql = "UPDATE t_user_data set last_login_time = '%s' ,count_login = count_login +1 WHERE uid = '%d' " % (s_time, uid)        
        conn.query(sql) 
         
        tmpStrSql = "INSERT INTO t_log_login (uid,nickname,s_time,e_time,sumtime) VALUES(%d,'%s','%s','%s','%s')" % (uid, nickname, s_time, e_time, sumtime)
        #conn.query(tmpStrSql)
        util.SqlThread.addSqlStr(tmpStrSql) #线程写记录
        
        return True

    @staticmethod
    def countAge(strDay):
        '''根据生日计算年龄'''
        if strDay is None or strDay == 'None' or not strDay:
            return 0        
        st = int(strDay[0:4])
        et = int(time.strftime('%Y'))
        return et - st    
    
    @staticmethod    
    def check_get_data(request,cmd,json_data):
        tmpSendMsgUtil = util.SendMsgUtil(request)
        if not json_data:
            tmpSendMsgUtil.update_res('pam_err')
            tmpSendMsgUtil.send(cmd)
            return None
        u = UserManager.get_user_by_request(request)
        if not u:
            tmpSendMsgUtil.update_res('user_is_null')
            tmpSendMsgUtil.send(cmd)
            return None
        return True
    
    #更新用户记录   : 用户信息，房主信息，需要修改的列名，保存多少记录，新的记录，附加修改的列名如：'clean=50'
    @staticmethod    
    def set_user_rec(userinfo, roomer, col, nums=50, new_dic=None, col2=None):     
        uid = userinfo['uid']
        nickname = userinfo['nickname']
        roomer_uid = roomer['uid']
        last_all_rec = roomer.get(col)
        if last_all_rec:
            last_all_rec = json_decode(last_all_rec)
        else:
            last_all_rec = {}
        new_rec = {'uid':uid, 'nickname':nickname,'got':0, 'timeline':time.strftime('%Y-%m-%d %H:%M:%S')}
        if new_dic:
            for k, v in new_dic.iteritems():
                new_rec[k] = v
        rec = UserManager.get_user_rec_list(new_rec, nums, last_all_rec)
        
        conn = mysqlHelper.mysql()       
        
        tmpData = {}
        tmpData[col] = json_encode(rec)
        if col2:            
            if type(col2)==dict:
                for k,v in col2.iteritems():
                    tmpData[k] = v            
            else:
                tmpData = "`%s` ='%s' ,%s " % (col, conn.escape_string(json_encode(rec)), col2) 
            conn.upData("t_user_record", tmpData, " WHERE uid = %d" %roomer_uid,asyn=True)
        else:
            conn.upData("t_user_record", tmpData," WHERE uid = %d" %roomer_uid,asyn=True)
            
        return {'res':True,'last_rec_id':rec['last_rec_id']}
    
    
    #设置用户记录并返回新的记录不保存  new_rec 需要保存的记录，last_rec 历史所有记录 nums 总共存储的记录数（超过了则删除最早的一条）
    @staticmethod 
    def get_user_rec_list(new_rec={}, nums=50, last_rec=None):       
        #rec = {last_rec_id:1,log:[{rec_id:1,uid:1001,nickname:kaka,timeline:2011-11-03 15:00:00}]}
        last_rec_id = 1
        if last_rec:           
            last_rec_id = last_rec['last_rec_id'] + 1
            rec = last_rec
            rec['last_rec_id'] = last_rec_id
        else:
            rec = {"last_rec_id":last_rec_id, 'log':[]}       
        new_rec['rec_id'] = last_rec_id
        rec['log'].append(new_rec)
        if len(rec['log']) > nums:
            rec['log'].remove(rec['log'][0])       
        return rec   
    
    #------记录表---------------------------------------
    @staticmethod
    def updateLogTotal(typeName): 
        '''更新统计表'''
        #conn = mysqlHelper.mysql() 
        sql = "update t_log_total set count = count + 1 WHERE name = '%s';" % typeName
        #conn.query(sql)
        util.SqlThread.addSqlStr(sql) #线程写记录
    
    @staticmethod
    def updateLogTotalBarTalking(): 
        '''更新统计表--邂逅总数'''
        UserManager.updateLogTotal("total_bar_talking")
    @staticmethod
    def updateLogTotalBarAddtime(): 
        '''更新统计表--续杯总数'''
        UserManager.updateLogTotal("total_bar_addtime")    
    @staticmethod
    def updateLogTotalBarPK(): 
        '''更新统计表--插足总数'''
        UserManager.updateLogTotal("total_bar_pk")    
    @staticmethod
    def updateLogTotalBarPKSuccess(): 
        '''更新统计表--插足成功总数'''
        UserManager.updateLogTotal("total_bar_pk_success")    
    @staticmethod
    def updateLogTotalHomeVisite(): 
        '''更新统计表--拜访总数'''
        UserManager.updateLogTotal("total_home_visite")    
    @staticmethod
    def updateLogTotalHomeClean(): 
        '''更新统计表--打扫总数'''
        UserManager.updateLogTotal("total_home_clean")    
    @staticmethod
    def updateLogTotalPhoto(): 
        '''更新统计表--相片总数'''
        UserManager.updateLogTotal("total_photo")
        
    @staticmethod
    def updateLogTotalPhotoDel(): 
        '''更新统计表--相片总数减一'''
        #conn = mysqlHelper.mysql()  
        sql = "update t_log_total set count = count - 1 WHERE name = 'total_photo';" 
        #conn.query(sql)
        util.SqlThread.addSqlStr(sql) #线程写记录
         
    @staticmethod
    def insertLogBarTalking(tmpExitUser, tmpNotExitUser, add_time, exitType, add_time_pay, s_time, e_time, sumtime): 
        '''插入酒吧邂逅记录表'''   
        if tmpExitUser is None or tmpNotExitUser is None:
            return
        try:
            conn = mysqlHelper.mysql()
            
            ExitUserUID = tmpExitUser.getUID()
            ExitUserNickname = tmpExitUser.getNickname()
            ExitUserSex = tmpExitUser.getSex()
            
            NotExitUserUID = tmpNotExitUser.getUID()
            NotExitUserNickname = tmpNotExitUser.getNickname()
            NotExitUserSex = tmpNotExitUser.getSex()
            
            #--记录个人的聊天次数
            conn.upData('t_user_data', {"count_room":1}, "WHERE uid in (%d, %d)" % (ExitUserUID, NotExitUserUID), 1)
            
            #--记录聊天约会信息
            sql = "insert into t_log_bar_talking(invite_uid, invite_nickname, invite_sex, invited_uid, invited_nickname, invited_sex, add_time, exit_type, add_time_pay, s_time, e_time, sumtime) \
             values('%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s')"  % (ExitUserUID, ExitUserNickname, ExitUserSex, NotExitUserUID, NotExitUserNickname, NotExitUserSex, add_time, exitType, add_time_pay, s_time, e_time, sumtime)
            #conn.query(sql)
            util.SqlThread.addSqlStr(sql) #线程写记录
        except Exception:
            log.print_error(logger, 'insertLogBarTalking error:\n%s' % traceback.format_exc())
         
    
    @staticmethod
    def updateLogTotalEveryday(tmpCmd, tmpGold, tmpMoney):
        '''更新统计每天系统赠送/消耗的金币, 比索'''
        if tmpGold == 0 and tmpMoney == 0:
            return
        tmpMap = {}
        if tmpGold > 0 and tmpCmd not in const.Config_Gold_not_sys_provide_cmd_list: #非赠送金币的命令字
            tmpMap["gold_sys_provide"] = tmpGold
        if tmpGold < 0 and tmpCmd not in const.Config_Gold_not_use_cmd_list:         #非消耗金币的命令字
            tmpMap["gold_use"] = tmpGold
            
        if tmpMoney > 0 and tmpCmd not in const.Config_Money_not_sys_provide_cmd_list: #非赠送比索的命令字
            tmpMap["money_pay"] = tmpMoney
        if tmpMoney < 0 and tmpCmd not in const.Config_Money_not_use_cmd_list:         #非消耗比索的命令字
            tmpMap["money_use"] = tmpMoney
            
        UserManager.updateLogTotalEverydayInfo(**tmpMap)
         
    @staticmethod
    def updateLogTotalEverydayInfo(**tmpMap): 
        '''更新统计每天系统表t_log_total_everyday'''
        if isinstance(tmpMap, dict) and len(tmpMap) > 0:
            tmpStr = " ";
            for tmpName, tmpCount in tmpMap.items():
                tmpStr = "%s %s = %s + %s," % (tmpStr, tmpName, tmpName, tmpCount)
            tmpStr = tmpStr[0:-1]
            
            strCurrentDateTime = util.getCurrentDatetimeToStr()
            sql = "update t_log_total_everyday set " + tmpStr  + " where date_format(s_time, '%Y-%m-%d') = date_format('"+ strCurrentDateTime +"', '%Y-%m-%d')"
           
            util.SqlThread.addSqlStr(sql) #线程写记录       
         
         
    @staticmethod
    def updateUserCount(field, counts, uid):
        '''增加用户统计数量'''
        conn = mysqlHelper.mysql()
        conn.upData('t_user_data', {field:counts}, " WHERE uid = %d"%uid, True);
        UserManager.update_user(uid, {field:counts},True)  #更新用户基本资料到缓存
        
    @staticmethod
    def updateDBUserMyAtttAndMyFriendAndAtttMe(tmpUser):
        '''更新用户 我的关注 和我的好友 , 关注我的  字段'''
        if not tmpUser:
            return
        conn = mysqlHelper.mysql()
        tmpDataDict = {}
        tmpDataDict["my_friend"] = json_encode(tmpUser.m_map_my_friend)
        tmpDataDict["my_attt"] = json_encode(tmpUser.m_map_my_attt)
        tmpDataDict["attt_me"] = json_encode(tmpUser.m_map_attt_me)
        tmpDataDict["my_hidden_love"] = json_encode(tmpUser.m_map_my_hidden_love)
        tmpDataDict["hidden_love_me"] = json_encode(tmpUser.m_map_hidden_love_me)
        conn.upData('t_user_record', tmpDataDict, "WHERE uid = '%d'" % tmpUser.getUID())
        
    @staticmethod
    def sendLogFriendInfoUrl(tmpUID, tmpNickname, tmpCmd, tmpTargetUID=None):
        tmpURL = const.ConfigLogFriendInfoUrl #URL
        tmpHTTPURLParms = {}
        tmpHTTPURLParms["uid"] = tmpUID
        tmpHTTPURLParms["nickname"] = tmpNickname
        tmpHTTPURLParms["timeline"] = int(time.time())
        tmpHTTPURLParms["cmd"] = tmpCmd
        if tmpTargetUID:
            tmpHTTPURLParms["target_uid"] = tmpTargetUID
        util.asynOpenUrl(tmpURL, 'POST', tmpHTTPURLParms) 

    @staticmethod
    def saveUserRemarkInfoToDB(tmpUser):
        '''保存些备注信息, 比如是否得到等级礼包'''
        if tmpUser:
            conn = mysqlHelper.mysql()
            tmpDataDict = {}
            tmpDataDict["remark_info"] = json_encode(tmpUser.getRemarkInfo())
            conn.upData('t_user_data', tmpDataDict, " WHERE uid = %d" % tmpUser.getUID());
            
    @staticmethod
    def updateDBUserMyNeighbor(tmpUser):
        '''更新用户 我的邻居  字段'''
        if not tmpUser:
            return
        conn = mysqlHelper.mysql()
        tmpDataDict = {}
        tmpDataDict["my_neighbor"] = json_encode(tmpUser.getMyNeighbor())
        conn.upData('t_user_record', tmpDataDict, "WHERE uid = '%d'" % tmpUser.getUID())
        
        